package com.intel.factorytest.activity;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.intel.factorytest.R;
public class CompassTest extends Activity  {


    private TextView intel_mat_mInfo ;
    private int intel_mat_count =0;
    private static final String TEST_ITEM = "test_item";
    private static final String TEST_ITEM_RESULT = "test_item_result";
    private boolean is_pass;
    private static final String TEST_RESULT = "test_result";
    
    private SensorManager mSensorManager;
 
    private Sensor accelerometer; // 加速度传感器
    private Sensor magnetic; // 地磁场传感器
 
    private float[] accelerometerValues = new float[3];
    private float[] magneticFieldValues = new float[3];


    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        intel_mat_mInfo = new TextView(this);
        intel_mat_mInfo.setTextSize(24.0f);
        intel_mat_mInfo.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
        intel_mat_mInfo.setGravity(Gravity.CENTER);
        setContentView(intel_mat_mInfo);
        
        // 实例化传感器管理者
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // 初始化加速度传感器
        accelerometer = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // 初始化地磁场传感器
        magnetic = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
 
        calculateOrientation();

    }

    @Override
    protected void onResume() {

        // TODO Auto-generated method stub
        // 注册监听
        mSensorManager.registerListener(new MySensorEventListener(),
                accelerometer, Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(new MySensorEventListener(), magnetic,
                Sensor.TYPE_MAGNETIC_FIELD);
        super.onResume();
   
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        // 解除注册
        mSensorManager.unregisterListener(new MySensorEventListener());

        super.onPause();
    
    } 
    
    // 计算方向
    private void calculateOrientation() {
        float[] values = new float[3];
        float[] R = new float[9];
        SensorManager.getRotationMatrix(R, null, accelerometerValues,
                magneticFieldValues);
        SensorManager.getOrientation(R, values);
        values[0] = (float) Math.toDegrees(values[0]);
        values[1] = (float) Math.toDegrees(values[1]);
        values[2] = (float) Math.toDegrees(values[2]);
        String intel_mat_tmp = values[0] +"\n"+values[1]+"\n"+values[2]+"\n";
        if(intel_mat_count >= 40) {
            
            TestResult(intel_mat_tmp);
            is_pass = true;
        }
        intel_mat_mInfo.setText(intel_mat_tmp);
    
    }
 
    class MySensorEventListener implements SensorEventListener {
        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                accelerometerValues = event.values;
            }
            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                magneticFieldValues = event.values;
            }
            intel_mat_count++;
            calculateOrientation();
        }
 
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub
 
        }
 
    }


 

    private void TestResult(String result) {
        String message = "";
        if(!is_pass){
            return;
        }
        File mFile = new File("/mnt/sdcard/compass.txt");
        //判断文件是否存在
        if (mFile.exists()) {
           // mFile.delete();
            return;
        }
        
        message = result + " \n" +" Compass Test is pass ";
        try {
            //创建文件
            mFile.createNewFile();
            RandomAccessFile raf = new RandomAccessFile(mFile, "rwd");
            raf.seek(mFile.length());
            raf.write(message.getBytes());
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected Dialog onCreateDialog(int none)
    {        
        return new AlertDialog.Builder(this)
//        .setIcon(R.drawable.alert_dialog_icon)
        .setTitle(R.string.SERVICEMENU_DIALOG_TITLE_TXT)
        .setPositiveButton(R.string.SERVICEMENU_DIALOG_YES_TXT, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                /* User clicked OK so do some stuff */
                finish();
            }
        })
        .setNegativeButton(R.string.SERVICEMENU_DIALOG_NO_TXT, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                /* User clicked Cancel so do some stuff */
                finish();
            }
        })
        .create();
    }
    
    private void setTestResult () {
        Intent intent = new Intent();
        Intent mIntent = getIntent();
        int pos = mIntent.getIntExtra(TEST_ITEM,-1);
        intent.putExtra(TEST_ITEM,pos);
        intent.putExtra(TEST_ITEM_RESULT,is_pass);
//        Log.e(TAG,"pos ="+pos);
        setResult(0, intent);
    }
    @Override
    public void finish() {
        setTestResult (); 
        super.finish();
    }
    public boolean ac_ispass() {
        return is_pass;
    } 
}
